<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="10">
          <el-input v-model="queryInfo.query" clearable @clear="getuserlist">
            <template #append>
              <el-button icon="el-icon-search" @click="getuserlist"></el-button>
            </template>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addUserVisible=true">添加用户</el-button>
        </el-col>
      </el-row>

      <el-table :data="userlist" border stripe >
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="editUser(scope.row.id)"></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteUser(scope.row.id)"></el-button>
            
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="setUser(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>

      <el-card class="Cardactive" v-show="addUserVisible">
        <template #header>
          <div class="card-header">
            请填写新用户的信息
          </div>
        </template>
        <div class="text item">
          <el-form :model="adduserForm" :rules="adduserrules" ref="adduserForm" label-width="70px">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="adduserForm.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="adduserForm.password"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="adduserForm.email"></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="mobile">
              <el-input v-model="adduserForm.mobile"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <el-button @click="cancel">取消</el-button>
        <el-button @click="confirm">确认</el-button>
      </el-card> 

      <el-card class="Cardactive" v-show="editUserVisible">
        <template #header>
          <div class="card-header">
            请修改用户信息
          </div>
        </template>
        <div class="text item">
          <el-form :model="edituserForm" :rules="edituserrules" ref="edituserForm" label-width="70px">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="edituserForm.username" disabled></el-input>
            </el-form-item>
            <el-form-item label=手机号 prop="mobile">
              <el-input v-model="edituserForm.mobile"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="edituserForm.email"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <el-button @click="cancel">取消</el-button>
        <el-button @click="editconfirm">确认</el-button>
      </el-card> 

      <el-dialog
        title="提示"
        :visible.sync="setuserVisible"
        width="60%">
        <p>当前的用户：{{setuserInfo.username}}</p>
        <p>当前的角色：{{setuserInfo.role_name}}</p>
        <el-select v-model="setroleid" placeholder="请选择">
          <el-option
            v-for="item in roleslist"
            :key="item.id"
            :label="item.roleName"
            :value="item.id">
          </el-option>
        </el-select>
        <span slot="footer" class="dialog-footer">
          <el-button @click="setuserVisible = false">取 消</el-button>
          <el-button type="primary" @click="setuserconfirm">确 定</el-button>
        </span>
      </el-dialog>

    </el-card>
     
      

  </div>
</template>

<script>
export default {
  name: "user",
  data(){

    var checkEmail = (rule,value,cb)=>{
      var regEmail = /^[A-Za-z0-9]+([_\.][A-Za-z0-9]+)*@([A-Za-z0-9\-]+\.)+[A-Za-z]{2,6}$/;
      if(regEmail.test(value)){
        return cb();
      }
      cb(new Error("请输入合法邮箱"))
    }

    var checkMobile = (rule,value,cb)=>{
      var regMobile = /^1[3|4|5|7|8][0-9]{9}$/;
      if(regMobile.test(value)){
        return cb();
      }
      cb(new Error("请输入合法的手机号"))
    }

    return {
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 2
      },
      userlist: [],
      total: 0,
      addUserVisible: false,
      editUserVisible: false,
      setuserVisible: false,
      adduserForm: {
        username: "",
        password: "",
        mobile: "",
        email: ""
      },
      edituserForm: {},
      adduserrules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入用户密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile,trigger: "blur"}
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail,trigger: "blur"}
        ]
      },
      edituserrules: {
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile,trigger: "blur"}
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail,trigger: "blur"}
        ]
      },

      setuserInfo: {},
      roleslist: [],
      setroleid: '',
    }
  },
  created() {
    this.getuserlist();
  },

  methods: {
    async getuserlist(){
      const { data: res } = await this.$http.get("/users",{params: this.queryInfo});
      // console.log(res);
      if(res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.userlist = res.data.users;
      this.total = res.data.total;
      this.$message.success("获取用户列表成功")
      // console.log(this.userlist,this.total);
    },
    handleSizeChange(newsize){
      this.queryInfo.pagesize = newsize;
      this.getuserlist();
    },
    handleCurrentChange(newpage){
      this.queryInfo.pagenum = newpage;
      this.getuserlist();
    },

    async userStateChange(userInfo){
      const {data: res} = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
      if(res.meta.status !== 200){
        userInfo.mg_state = !userInfo.mg_state;
        return this.$message.error(res.meta.msg);
      }
      this.$message.success(res.meta.msg);
    },

    cancel(){
      this.addUserVisible = false;
      this.editUserVisible = false;
      this.deleteUserVisible = false;
      this.setUserVisible = false;
      this.$refs.adduserForm.resetFields();
      this.$refs.edituserForm.resetFields();
    },

    confirm(){
      this.$refs.adduserForm.validate(async valid=>{
        if(valid){
          const{ data: res} = await this.$http.post("/users",this.adduserForm);
          // console.log(res);
        }
      })
      this.getuserlist()
      this.addUserVisible = false;
      this.$refs.adduserForm.resetFields();
    },

    editconfirm(){
      this.$refs.edituserForm.validate(async valid=>{
        if(!valid) return this.$message.error("请输入正确的信息");
        const {data : res} = await this.$http.put("/users/"+this.edituserForm.id,{
          email: this.edituserForm.email,
          mobile: this.edituserForm.mobile
        });
        // console.log(res);
        if(res.meta.status !== 200) return this.$message.error("更改信息失败")
        this.getuserlist()
        this.editUserVisible = false;
        this.$refs.edituserForm.resetFields();
        this.$message.success("更改信息成功")
      })
      
    },

    async editUser(id){
      this.editUserVisible = true;
      const {data: res} = await this.$http.get("/users/"+id);
      this.edituserForm = res.data;
      console.log(this.edituserForm);
    },
    deleteUser(id){
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
      }).then(res => {
          this.$http.delete("/users/"+id).then(res=>{
             if(res.status !== 200) return this.$message.error("删除失败");
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              this.getuserlist();
            // console.log(res);
          }).catch(err=>console.log(err));         
        })
        .catch((err) => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },
    async setUser(user){
      this.setuserVisible = true;
      this.setuserInfo = user;

      const {data: res} = await this.$http.get("/roles");
      this.roleslist = res.data;
      // console.log(res);
      // console.log(this.setuserInfo);
    },

    async setuserconfirm(){
      if(!this.setroleid) return this.$message.error("请选择要设置的角色")
      this.setuserVisible = false;
      // console.log(this.setuserInfo,this.setroleid,this.roleslist);
      const {data: res} = await this.$http.put(`users/${this.setuserInfo.id}/role`,{
        rid: this.setroleid
      });
      // console.log(res);
      this.getuserlist();
    }
  }
}
</script>

<style scpoed>
  .box-card{
    margin-top: 30px;
    overflow: visible;
  }
  .el-table{
    font-size: 10px;
    margin-top: 30px;
  }
  .Cardactive{
    position: absolute;
    width: 70%;
    left: 50%;
    top: 50%;
    transform: translate(-50%,-50%);
    z-index: 999;
    text-align: center;
  }

  .box-card{
    position: relative;
  }

  .card-header{
    font-size: 14px;
    font-weight: 300;
  }
</style>